#include "rgb.h"
#include "temp.h"
#include "msgd.h"

static int fd_i2c;

static int rgbLogLevel = LOG_WARNING;

void setRGBLogLevel(int logLevel)
{
    rgbLogLevel = logLevel;
}


int initRGB()
{
    wiringPiSetup();
    fd_i2c = wiringPiI2CSetup(0x0d);
    if (fd_i2c < 0)
    {
        perr_d(true,rgbLogLevel,"function wiringPiI2CSetup error when called initRGB");
        return -1;
    }
    return 0;
}


void setRGB(int num, int R, int G, int B)
{
    if (num >= Max_LED)
        wiringPiI2CWriteReg8(fd_i2c, 0x00, 0xff);
    else if (num >= 0)
        wiringPiI2CWriteReg8(fd_i2c, 0x00, num);

    wiringPiI2CWriteReg8(fd_i2c, 0x01, R);
    wiringPiI2CWriteReg8(fd_i2c, 0x02, G);
    wiringPiI2CWriteReg8(fd_i2c, 0x03, B);
    return ;
}


void closeRGB()
{
    wiringPiI2CWriteReg8(fd_i2c, 0x07, 0x00);
}


void setRGBEffect(int effect)
{
    if (effect >= 0 && effect <= 4)
    {
        wiringPiI2CWriteReg8(fd_i2c, RGB_Effect, effect);
    } 
}

void setRGBSpeed(int speed)
{
    if (speed >= 1 && speed <= 3)
    {
        wiringPiI2CWriteReg8(fd_i2c, RGB_Speed, speed);
    }
}

void setRGBColor(int color)
{
    if (color >= 0 && color <= 6)
    {
        wiringPiI2CWriteReg8(fd_i2c, RGB_Color, color);
    }
}

void tempRGB()
{
    int temp = getTempLevel();

    if(temp == TEMP_FREEZING)//深蓝色 temp < 40
        setRGB(Max_LED, 0x00, 0x00, 0xff);

    if(temp == TEMP_NORMAL_LOW)//深绿色 temp [40,45)
        setRGB(Max_LED,0x00,0xff,0x00);

    if(temp == TEMP_NORMAL_MIDDLE)//青色 temp [45,50)
        setRGB(Max_LED,0x00,0xff,0xff);

    if(temp == TEMP_NORMAL_HIGH)//黄色 temp [50,55)
        setRGB(Max_LED,0xff,0xff,0x00);

    if(temp == TEMP_GREAT_HIGH)//粉红色 temp [55,60)
        setRGB(Max_LED,0xff,0x00,0xff);

    if(temp == TEMP_EXTREME_HIGH)//大红色 temp [60,~)
        setRGB(Max_LED,0xff,0,0);

    return ;
}

extern pthread_barrier_t thread_wait;
void * tempRGB_thread(void * sleep_second)
{
    int slp = 5;
    if(sleep_second != NULL)
        slp = *(int *)sleep_second;
    while(1)
    {
        pthread_barrier_wait(&thread_wait);
        tempRGB();
        sleep(slp);
    }
    return NULL;
}